package handler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"post-mgmt/cache"
	"post-mgmt/model"
	"strconv"
	"time"
)

func List(c *gin.Context) {
	var article []model.Article

	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	offset := (page - 1) * size
	redis_list_key := "list_page_" + strconv.Itoa(page)
	result, _ := cache.Rdb.Get(cache.Ctx, redis_list_key).Result()
	if result == "" {
		model.DB.Offset(offset).Limit(size).Debug().Find(&article)
		jsonData, _ := json.Marshal(article)
		cache.Rdb.Set(cache.Ctx, redis_list_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(result), &article)
	}
	var total int64
	model.DB.Model(&model.Article{}).Count(&total)

	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "succe
		"data":  article,
	})
	return
}
func Detail(c *gin.Context) {
	id := c.Query("id")
	var article model.Article
	model.DB.Where("id=?", id).First(&article)

	redis_list_key := "detail_" + id
	result, _ := cache.Rdb.Get(cache.Ctx, redis_list_key).Result()
	if result == "" {
		model.DB.Where("id=?", id).First(&article)
		jsonData, _ := json.Marshal(article)
		cache.Rdb.Set(cache.Ctx, redis_list_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(result), &article)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "success",
		"data": article,
	})
	return

}
